package issr.market.utils;

import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.ConvertUtils;
import org.displaytag.decorator.DisplaytagColumnDecorator;
import org.displaytag.properties.MediaTypeEnum;

public class CSVWriter {
	
	
	public static void writeHeader(final List<String> printableKeys, Writer writer)
			throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, IOException {
		StringBuffer sb = new StringBuffer();

		for (String propertyKey : printableKeys) {
			addCsvColumn(sb, propertyKey);
		}
		Utils.removeLastChar(sb);
		sb.append(Constants.CSV_NEWLINE);
		writer.write(sb.toString());
	}

	
	
	public static StringBuffer printPrintableKeys(final List<String> printableKeys, Map<String, Object> propertiesMap, StringBuffer sb, MediaTypeEnum media)
			throws IOException {
		for (String printableKey : printableKeys) {
			Object value = propertiesMap.get(printableKey);
			String converted = convertByDecorator(printableKey, value,media);
			if (converted == null) {
				converted = "";
			}
			addCsvColumn(sb, converted);
		}
		return sb;
	}

	
	public static  void addCsvColumn(StringBuffer sb, String value) throws IOException {
		sb.append(Constants.CSV_WRAPPER);
		sb.append(value);
		sb.append(Constants.CSV_WRAPPER);
		sb.append(Constants.CSV_SEPARATOR);
	}
	
	private static String convertByDecorator(String decoratorKey, Object value, MediaTypeEnum media) {

		if (decoratorKey == null || decoratorKey.length() == 0)
			return ConvertUtils.convert(value);

		if (media==null) media = MediaTypeEnum.CSV;
		DisplaytagColumnDecorator decorator = Utils.getDecoratorByProperty(decoratorKey + ".decorator");
		try {

			String v = (String) decorator.decorate(value, null, media);
			return v;
		} catch (Exception e) {
			if (decoratorKey.indexOf("importo") > 0)
				e.printStackTrace();
			return ConvertUtils.convert(value);
		}
	}

}
